package org.linlinjava.litemall.db.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.dao.LitemallCategoryMapper;
import org.linlinjava.litemall.db.domain.LitemallCategory;
import org.linlinjava.litemall.db.domain.LitemallCategoryExample;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallGoodsExample;
import org.linlinjava.litemall.db.vo.CatVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;



@Service
public class LitemallCategoryService {
	
    @Resource
    private LitemallCategoryMapper categoryMapper;
    private LitemallCategory.Column[] CHANNEL = {LitemallCategory.Column.id, LitemallCategory.Column.name, LitemallCategory.Column.iconUrl};

    public List<LitemallCategory> selectList(){
        return this.categoryMapper.selectList(null);
    }

    public List<LitemallCategory> selectCategoryByIdsInL3(List<Integer> ids){
        return categoryMapper.selectList(Wrappers.lambdaQuery(LitemallCategory.class)
                .in(LitemallCategory::getId,ids)
                .eq(LitemallCategory::getLevel,"L3"));
    }

    public List<LitemallCategory> queryL1WithoutRecommend(int offset, int limit) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andLevelEqualTo("L1").andNameNotEqualTo("推荐").andDeletedEqualTo(false);
        //PageHelper.startPage(offset, limit);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryL1(int offset, int limit) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andLevelEqualTo("L1").andDeletedEqualTo(false);
        //PageHelper.startPage(offset, limit);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryL1() {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.orderBy("sort_order asc,add_time asc");
        example.or().andLevelEqualTo("L1").andDeletedEqualTo(false);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryByLevel(String level) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andLevelEqualTo(level).andDeletedEqualTo(false);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryByPid(Integer pid) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.orderBy("sort_order asc,add_time asc");
        example.or().andPidEqualTo(pid).andDeletedEqualTo(false);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryL2ByIds(List<Integer> ids) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andIdIn(ids).andLevelEqualTo("L2").andDeletedEqualTo(false);
        return categoryMapper.selectByExample(example);
    }

    public LitemallCategory findById(Integer id) {
        return categoryMapper.selectById(id);
    }

    public List<LitemallCategory> findCategoryHierarchy(Integer id) {
        List<LitemallCategory> categoryList = new ArrayList<>();

        // 递归查找分类的父级目录
        LitemallCategory category = this.findById(id);

        while (category != null) {
            categoryList.add(category);  // 添加当前分类

            // 如果当前分类是一级目录，停止递归
            if (category.getLevel() == Constants.CATEGORY_LEVEL_L1) {
                break;
            }

            // 查找父级目录
            category = this.findById(category.getPid());
        }

        // 返回从三级到一级的目录列表（根据需要可以反转顺序）
        CollUtil.reverse(categoryList);  // 如果需要从L1到L3的顺序，则需要反转列表
        return categoryList;
    }


    public List<LitemallCategory> querySelective(String id, String name, Integer page, Integer size, String sort, String order) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        LitemallCategoryExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(id)) {
            criteria.andIdEqualTo(Integer.valueOf(id));
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        //PageHelper.startPage(page, size);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> querySelective(List<Integer> ids, Integer page, Integer size, String sort, String order) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        LitemallCategoryExample.Criteria criteria = example.createCriteria();

        if (ids != null && ids.size() > 0) {
            criteria.andIdIn(ids);
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        //PageHelper.startPage(page, size);
        return categoryMapper.selectByExample(example);
    }

    public int updateById(LitemallCategory category) {
        category.setUpdateTime(LocalDateTime.now());
        return categoryMapper.updateByPrimaryKeySelective(category);
    }

    public void deleteById(Integer id) {
        categoryMapper.logicalDeleteByPrimaryKey(id);
    }

    public void add(LitemallCategory category) {
        category.setAddTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.insertSelective(category);
    }

    public List<LitemallCategory> queryChannel() {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andLevelEqualTo("L1").andDeletedEqualTo(false);
        return categoryMapper.selectByExampleSelective(example, CHANNEL);
    }

    public List<LitemallCategory> queryByName(String name){
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andNameEqualTo(name).andDeletedEqualTo(false);
        return categoryMapper.selectByExampleSelective(example);
    }

    public List<LitemallCategory> findByIds(List<Integer> categoryIds) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andIdIn(categoryIds).andDeletedEqualTo(false);
        return categoryMapper.selectByExample(example);
    }

    public String[] getByIds(String[] goodsValue) {
        List<LitemallCategory> litemallCategories = categoryMapper.selectBatchIds(Arrays.asList(goodsValue));
        if (litemallCategories!=null&&!litemallCategories.isEmpty()){
            List<String> collect = litemallCategories.stream().map(category -> category.getName()).collect(Collectors.toList());
            return collect.toArray(new String[collect.size()]);
        }
        return new String[]{};
    }

    public List<CatVo> categoryThreeLinkage() {
        //一级
        List<CatVo> catVoList = categoryMapper.selectList(new LambdaQueryWrapper<LitemallCategory>().eq(LitemallCategory::getPid, 0)).stream().filter(litemallCategoryThree -> !litemallCategoryThree.getDeleted()).map(litemallCategory -> {
            CatVo catVo = new CatVo();
            catVo.setValue(litemallCategory.getId());
            catVo.setLabel(litemallCategory.getName());
            //二级
            List<CatVo> collectSecond = categoryMapper.selectList(new LambdaQueryWrapper<LitemallCategory>().eq(LitemallCategory::getPid, litemallCategory.getId())).stream().filter(litemallCategoryThree -> !litemallCategoryThree.getDeleted()).map(litemallCategorySecond -> {
                CatVo catVoSecond = new CatVo();
                catVoSecond.setValue(litemallCategorySecond.getId());
                catVoSecond.setLabel(litemallCategorySecond.getName());
                //三级
                List<CatVo> collectThree = categoryMapper.selectList(new LambdaQueryWrapper<LitemallCategory>().eq(LitemallCategory::getPid, litemallCategorySecond.getId())).stream().filter(litemallCategoryThree -> !litemallCategoryThree.getDeleted()).map(litemallCategoryThree -> {
                    CatVo catVoThree = new CatVo();
                    catVoThree.setValue(litemallCategoryThree.getId());
                    catVoThree.setLabel(litemallCategoryThree.getName());
                    return catVoThree;
                }).collect(Collectors.toList());
                catVoSecond.setChildren(collectThree);
                return catVoSecond;
            }).collect(Collectors.toList());
            catVo.setChildren(collectSecond);
            return catVo;
        }).collect(Collectors.toList());
        return catVoList;
    }
}
